import { FC, StrictMode, useEffect, useState } from 'react';
import { RecoilRoot } from 'recoil';
import { BrowserRouter as Router } from 'react-router-dom';
import RootRouter from './root.route';
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';

import '../locale';
import microApp from '@micro-zoe/micro-app';
import config from '../../bin/local.config';
import '../style/page.scss'

const App: FC = () => {
    const queryClient = new QueryClient()
    const [scale, setScale] = useState<string>('1')
    let timeout: NodeJS.Timeout | number = 0
    let wsTime: NodeJS.Timeout | number = 0
    const win: any = window
    useEffect(() => {
        if (win.__MICRO_APP_BASE_URL__) {
            microApp.start({
                ssr: true,
                tagName: "lh-form"
            })
        }
        win.addEventListener('resize', onDefer)
        resize();
        let ws: any = null
        if (module.hot) {
            ws = new WebSocket(`ws://${config.host}:${config.port}/rsbuild-hmr`)
            ws.onopen = function() {
                ws.send('监听')
            }
            ws.onmessage = function(res: any) {
                try {
                    const data = JSON.parse(res.data)
                    if (data.type === 'ok') {
                        clearTimeout(wsTime)
                        wsTime = setTimeout(() => {
                            if (win.microApp) {
                                win.microApp.dispatch({
                                    type: 'render'
                                })
                            }
                        }, 50)
                    }
                } catch(e) {
                    console.error(e)
                }
            }
        }
        return () => {
            win.removeEventListener('resize', onDefer)
            clearTimeout(timeout);
            ws && ws.close();
            clearTimeout(wsTime);
        }
    }, [])
    const onDefer = () => {
        clearTimeout(timeout)
        timeout = setTimeout(() => {
            resize();
        }, 50)
    }
    const resize = () => {
        const html = document.documentElement;
        if (html.clientWidth >= 960) {
            html.style.fontSize = `${(html.clientWidth / 1920).toFixed(5)}px`;
            setScale((html.clientWidth / 1920).toFixed(5));
        }
    }
    return (<StrictMode>
        <QueryClientProvider client={queryClient}>
            <RecoilRoot>
                <Router basename={win.__MICRO_APP_BASE_URL__ || '/'} future={{
                    v7_startTransition: true,
                    v7_relativeSplatPath: true
                }}>
                    <RootRouter scale={scale} />
                </Router>
            </RecoilRoot>
        </QueryClientProvider>
    </StrictMode>)
}

export default App